`
https://leetcode.cn/problems/take-k-of-each-character-from-left-and-right/
`

/**
 * @param {string} s
 * @param {number} k
 * @return {number}
 */
var takeCharacters = function (s, k) {
  // 等价于去掉中间的一段，使得剩下的字符串至少有 k 个 a, b, c
  const n = s.length
  const needs = new Map()
  for (const c of s) {
    needs.set(c, (needs.get(c) || 0) + 1)
  }
  for (const c of 'abc') {
    needs.set(c, (needs.get(c) || 0) - k)
    // 字符里没有足够的字符取出
    if (needs.get(c) < 0) return -1
  }
  const cnt = new Map()
  let res = 0
  let left = 0, right = 0

  while (right < n) {
    const c = s[right++]
    cnt.set(c, (cnt.get(c) || 0) + 1)

    // 窗口内的字符数量不能超过 needs 里的，超过就需要收缩
    while (cnt.get(c) > needs.get(c)) {
      const d = s[left++]
      cnt.set(d, cnt.get(d) - 1)
    }

    res = Math.max(res, right - left)
  }

  return n - res
};